package com.xing.okhttp;

import okhttp3.Response;
import okhttp3.ResponseBody;
import org.json.simple.JSONValue;

import java.io.*;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.GZIPInputStream;

public class HttpClientHelper {


    /**
     * 获取输出流，如果使用默认的压缩编码，创建并返回压缩的输出流，否则从http连接里获得输出流
     *
     * @param encoding
     * @return
     * @throws IOException
     */
    private static OutputStream getOutputStream(OutputStream out, String encoding) throws IOException {
        if ("deflate".equals(encoding))
            return new DeflaterOutputStream(out, new Deflater(-1));
        else
            return out;
    }


    public static byte[] writeData(String encoding, Object params) throws IOException {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        Writer out = null;
        OutputStream os = null;
        try {
            os = getOutputStream(outStream, encoding);
            out = new OutputStreamWriter(os, "UTF-8");
            JSONValue.writeJSONString(params, out);
            out.flush();
        } finally {
            if (out != null)
                out.close();

            if (os != null) {
                os.close();
            }

        }
        return outStream.toByteArray();
    }


    /**
     * 从http连接里读取响应信息
     *
     * @param response
     * @return
     * @throws Exception
     */
    public static String readResponseBody(Response response) throws Exception {
        ResponseBody body = response.body();
        if (body == null) {
            return "";
        }
        InputStream is = body.byteStream();
        BufferedReader in = getBufferedReader(response, is);
        StringBuffer sb = new StringBuffer();
        try {
            String s;
            while((s = in.readLine()) != null) {
                sb.append(s);
            }
        } finally {
            in.close();
            is.close();
        }
        return sb.toString();
    }

    /**
     * 获取输入流，如果响应信息使用压缩格式，则创建压缩的输入流，否则创建缓存输入流
     *
     * @param is
     * @return
     * @throws IOException
     */
    private static BufferedReader getBufferedReader(Response response, InputStream is) throws IOException {
        String encodingHeader = response.header("content-encoding");
        if (encodingHeader != null) {
            if ("gzip".equals(encodingHeader))
                is = new GZIPInputStream(is);
        }
        return new BufferedReader(new InputStreamReader(is, "UTF-8"));
    }
}
